package org.xs.web.http;

import java.io.IOException;
import java.io.OutputStream;

import org.xs.web.http.provider.HTTPCookie;
import org.xs.web.http.provider.HTTPHeader;
import org.xs.web.http.provider.HTTPResponse;

public class StreamingResponse implements XSResponse{
	private int code;
	private byte[] outs = new byte[0];
	private HTTPHeader[] headers;
	private HTTPCookie[] cookies;
	private String contentType;
	
	public StreamingResponse(byte[] bytes,String contentType,int code,HTTPHeader[] headers,HTTPCookie[] cookies){
		this.outs = bytes;
		this.contentType = contentType;
		this.code = code;
		this.headers = headers;
		this.cookies = cookies;
	}
	
	public StreamingResponse(byte[] bytes,int code){
		this(bytes,"",code,new HTTPHeader[0],new HTTPCookie[0]);
	}
	
	public StreamingResponse(byte[] bytes,String contentType,HTTPHeader[] headers,HTTPCookie[] cookies){
		this(bytes,contentType,200,headers,cookies);
	}
	public StreamingResponse(byte[] bytes,String contentType,int code,HTTPHeader[] headers){
		this(bytes,contentType,code,headers,new HTTPCookie[0]);
	}
	
	public StreamingResponse(byte[] bytes,String contentType,HTTPHeader[] headers){
		this(bytes,contentType,200,headers,new HTTPCookie[0]);
	}
	
	public StreamingResponse(byte[] bytes,String contentType,int code){
		this(bytes,contentType,code,new HTTPHeader[0],new HTTPCookie[0]);
	}
	public StreamingResponse(byte[] bytes,String contentType){
		this(bytes,contentType,200,new HTTPHeader[0],new HTTPCookie[0]);
	} 
	
	@Override
	public int getCode() {
		return code;
	}

	@Override
	public String getContentType() {
		return contentType;
	}

	@Override
	public HTTPHeader[] getHeaders() {
		return headers;
	}

	@Override
	public boolean isJs() {
		return false;
	}

	@Override
	public boolean isStream() {
		return true;
	}

	@Override
	public boolean isTemplete() {
		return false;
	}

	@Override
	public boolean isText() {
		return false;
	}

	@Override
	public boolean isXml() {
		return false;
	}

	@Override
	public Object apply(HTTPResponse response) {
		response.addHeader(XSRules.defaultHeaders());
		response.addHeader(headers);
		response.addCookie(cookies);
		if(contentType != null && contentType.length() > 1){
			response.addHeader("Content-Type", contentType);
		}
		response.addHeader("Content-Length", String.format("%s", new Object[]{outs.length}));
		response.setStatus(code);
		try {
			OutputStream out = response.getDelegate().getOutputStream();
			out.write(outs);
			out.flush();
		} catch (IOException e) {
			 
		}
		return true;
	}
}
